package com.chinawu.cloud.ss.config.sharding;

import cn.hutool.core.util.ReflectUtil;
import com.chinawu.cloud.ss.service.TbShardingConfigService;
import org.apache.shardingsphere.core.rule.ShardingRule;
import org.apache.shardingsphere.core.rule.TableRule;
import org.apache.shardingsphere.core.strategy.route.ShardingStrategy;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.context.ShardingRuntimeContext;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.Optional;

/**
 * <p class="detail">
 * 功能：shardingsphere复合分片自定义分库分表配置查询服务注入
 * </p>
 *
 * @author wuyubin
 * Copyright 2021 chinawu.com, Inc. All rights reserved
 * @version V1.0
 * @ClassName: StartupConfig
 * @date 2021年07月28日 14:11
 */
@Component
public class StartupConfig {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private TbShardingConfigService tbShardingConfigServiceImpl;


    @PostConstruct
    public void init() {
        this.loadLogInit();
    }

    private void loadLogInit() {
        if (dataSource != null) {

            if (dataSource instanceof ShardingDataSource) {
                ShardingDataSource sds = (ShardingDataSource) dataSource;
                ShardingRuntimeContext shardingContext = sds.getRuntimeContext();
                ShardingRule shardingRule = shardingContext.getRule();
                Optional<TableRule> tableRules = shardingRule.findTableRule("tb_order");
                TableRule tableRule = tableRules.get();
                if (tableRule != null) {
                    ShardingStrategy dataBaseShardingStrategy = tableRule.getDatabaseShardingStrategy();
                    ShardingStrategy tableShardingStrategy = tableRule.getTableShardingStrategy();

                    ComplexOrderDbShardingAlgorithm complexOrderDbShardingAlgorithm = (ComplexOrderDbShardingAlgorithm) ReflectUtil.getFieldValue(dataBaseShardingStrategy, "shardingAlgorithm");
                    complexOrderDbShardingAlgorithm.init(tbShardingConfigServiceImpl);

                    ComplexOrderTbShardingAlgorithm complexOrderTbShardingAlgorithm = (ComplexOrderTbShardingAlgorithm) ReflectUtil.getFieldValue(tableShardingStrategy, "shardingAlgorithm");
                    complexOrderTbShardingAlgorithm.init(tbShardingConfigServiceImpl);
                }
            }
        }
    }
}
